/**
 * Created by tpig on 2017/1/6.
 */

var canvas;
var ctx;

var  testArray = [4, 10, 20, 13, 10, 9, 2, 16];

window.onload = function(){
    init();
    visualize(testArray, 100, 200, 500, 300);
    visualize([23,19,4,5], 500,200, 500, 300);
};

function init(){
    canvas = document.createElement("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    document.body.appendChild(canvas);

    ctx = canvas.getContext("2d");
}

function visualize(arr , top , left , width, height) {
    var max = arr[0];
    var min = arr[0];
    for(var i=0; i<arr.length; i++) {
        if(arr[i] < min) {
            min = arr[i];
        }
        if(arr[i] > max) {
            max = arr[i];
        }
    }

    min = 0;
    var dw = width / (arr.length + 1);
    var dh = height / (max - min);
    var base = min - (max - min) * 0.2;

    ctx.save();
    ctx.fillStyle = "#3e8e9b";
    for(var n=0; n<arr.length; n++) {
        var h = base + height * (arr[n] - min) / (max -min) ;
        ctx.fillRect(left + n* dw + dw/2,
                    top + height - h,
                    dw * 0.8,
                    h );

    }
    ctx.beginPath();
    ctx.moveTo(left, top);
    ctx.lineTo(left, top + height);
    ctx.lineTo(left + width, top+ height);
    ctx.stroke();

    ctx.restore();

}